<?php
/**
 * This file is part of webman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace app\middleware;


use support\Log;
use think\facade\Db;
use Tinywan\Jwt\JwtToken;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

/**
 * Class AuthCheck
 * @package app\middleware
 */
class AuthCheck implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        //在程序執行完成之後記錄
        Db::listen(function($sql, $runtime, $master) {
            // 进行监听处理
            Log::info('sql', [$sql, $runtime]);
        });

        try {
            $token = JwtToken::getCurrentId();
            if ($token) {
                // 已经登录，请求继续向洋葱芯穿越
                return $handler($request);
            }
        } catch (\Exception $e) {
            // 拦截请求，返回一个json，请求停止向洋葱芯穿越
            return json(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
        }

        // 不需要登录，请求继续向洋葱芯穿越
        return $handler($request);
    }
}
